use crate::minio::connect;
use crate::{ApiError, ApiResult, ToError, configuration};
use bytes::Bytes;
use minio::s3::builders::ObjectToDelete;
use minio::s3::response::{DeleteObjectResponse, GetObjectResponse, PutObjectResponse};
use minio::s3::segmented_bytes::SegmentedBytes;
use minio::s3::types::S3Api;

/// 上传文件
pub async fn put_object<S: Into<String>>(object: S, vec: Vec<u8>) -> ApiResult<PutObjectResponse> {
    let minio = configuration::minio();
    let bytes = SegmentedBytes::from(Bytes::from(vec));
    let put_object = connect::get().put_object(minio.bucket(), object, bytes);
    put_object
        .send()
        .await
        .to_err(|| ApiError::Biz("上传文件失败".into()))
}

/// 上传文件
pub async fn put_object_bytes<S: Into<String>>(object: S, bytes: Bytes) -> ApiResult<PutObjectResponse> {
    let minio = configuration::minio();
    let bytes = SegmentedBytes::from(bytes);
    let put_object = connect::get().put_object(minio.bucket(), object, bytes);
    put_object
        .send()
        .await
        .to_err(|| ApiError::Biz("上传文件失败".into()))
}

/// 获取文件
pub async fn get_object<S: Into<String>>(object: S) -> ApiResult<GetObjectResponse> {
    let minio = configuration::minio();
    let get_object = connect::get().get_object(minio.bucket(), object);
    get_object
        .send()
        .await
        .to_err(|| ApiError::Biz("获取文件失败".into()))
}

/// 删除文件
pub async fn delete_object<D: Into<ObjectToDelete>>(object: D) -> ApiResult<DeleteObjectResponse> {
    let minio = configuration::minio();
    let delete_object = connect::get().delete_object(minio.bucket(), object);
    delete_object
        .send()
        .await
        .to_err(|| ApiError::Biz("删除文件失败".into()))
}
